package chuan.application.NetWork;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class Network {
    private Handler mHandler;


    public Network(Handler hander, String url) {
        mHandler = hander;
        createNetwork(url);
    }

    private void createNetwork(final String strs) {
        new Thread() {
            @Override
            public void run() {

                Log.i("createNetwork", "URL=" + strs);
                String resultData = "";
                URL url = null;
                try {
                    //构造一个URL对象
                    url = new URL(strs);
                } catch (MalformedURLException e) {
                    Log.e("createNetwork", "URL 格式不规范" + e);
                    return;
                }

                try {
                    HttpURLConnection urlConn =
                            (HttpURLConnection) url.openConnection();
                    urlConn.setConnectTimeout(6 * 1000);
                    urlConn.setRequestMethod("GET");

                    InputStreamReader in =
                            new InputStreamReader(urlConn.getInputStream());
                    BufferedReader buffer = new BufferedReader(in);

                    String inputLine = null;
                    while (((inputLine = buffer.readLine()) != null)) {
                        resultData += inputLine;
                    }

                    in.close();
                    urlConn.disconnect();

                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = resultData;
                    mHandler.sendMessage(msg);

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
